package net.neptech.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.validation.Valid;
import net.neptech.bo.AddStaffBo;
import net.neptech.bo.StaffBo;
import net.neptech.bo.StaffInfoBo;
import net.neptech.dto.sys.StaffDTO;
import net.neptech.dto.workflow.UserQueryDto;
import net.neptech.model.sys.Staff;
import net.neptech.model.sys.User;
import net.neptech.page.PageQuery;
import net.neptech.page.TableDataInfo;
import net.neptech.service.*;
import net.neptech.utils.BeanCopyUtils;
import net.neptech.utils.SecurityUtils;
import net.neptech.utils.StreamUtils;
import net.neptech.vm.ResponseResult;
import net.neptech.vo.*;
import org.hibernate.sql.ast.tree.expression.Collation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author Saya
 * @Date 2025/8/13 17:33
 * @Description 职工查询接口
 **/
@RestController
@RequestMapping("system/staff")
public class StaffController {

    @Autowired
    private StaffService staffService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private StaffPositionService staffPositionService;
    @Autowired
    private UserService userService;

    @GetMapping("getExpert")
    public ResponseResult<List<StaffDTO>> getExpert() {
        return ResponseResult.success(staffService.getExpert());
    }

    @GetMapping("getStaff")
    public ResponseResult<List<StaffDTO>> getStaff() {
        return ResponseResult.success(staffService.getStaff());
    }

    @GetMapping("getStaff/{userId}")
    public ResponseResult<StaffDTO> getStaffByUserId(@PathVariable("userId") String userId) {
        return ResponseResult.success(getStaff().getData().stream().filter(staff -> staff.getUserId().equals(Long.getLong(userId))).findFirst().orElse(null));
    }

    @GetMapping("getRoleIds/{userId}")
    ResponseResult<List<String>> getRoleIdsByUserId(@PathVariable("userId") String userId) {
        return ResponseResult.success(roleService.selectRoleByStaffId(staffService.selectStaffById(Long.getLong(userId)).getStaffId()).stream().map(String::valueOf).toList());
    }

    @PostMapping("getUserIdsByDto")
    ResponseResult<List<String>> getUserIdsByDto(@RequestBody UserQueryDto userQueryDto) {
        List<Long> roleIds = userQueryDto.getRoleIdList();
        List<Long> deptIds = userQueryDto.getDeptIdList();
        if (!roleIds.isEmpty()) {
            roleIds = staffService.getIdsByRoleIds(roleIds);
        }
        if (!deptIds.isEmpty()) {
            deptIds = staffService.getIdsByDeptIds(deptIds);
        }
        Collection<Long> coll = CollectionUtil.intersection(roleIds, deptIds);
        List<Long> res = new ArrayList<>(coll);
        return ResponseResult.success(res.stream().map(String::valueOf).toList());
    }

    @GetMapping("getByDept/{deptId}")
    ResponseResult<List<StaffDTO>> getUserByDept(@PathVariable("deptId") String deptId) {
        return ResponseResult.success(getStaff().getData().stream().filter(s -> s.getDeptId().equals(Long.getLong(deptId))).toList());
    }

    @GetMapping("search/{keyword}")
    ResponseResult<List<StaffDTO>> searchStaff(@PathVariable("keyword") String userName){
        return ResponseResult.success(staffService.searchByName(userName));
    }

    @GetMapping("getByDeptId/{deptId}")
    public ResponseResult<List<Staff>> getByDeptId(@PathVariable("deptId") Long deptId) {
        return ResponseResult.success(staffService.getByDeptId(deptId));
    }

    @GetMapping("getStaffInfoByUserId/{userId}")
    public ResponseResult<Staff> getStaffInfoByUserId(@PathVariable("userId") Long userId) {
        System.out.println(SecurityUtils.getLoginUser());
        return ResponseResult.success(staffService.getStaffInfoByUserId(userId));
    }

    /**
     * 根据id查询多个医生详细信息 内部调用
     *
     * @return
     */
    @PostMapping("getStaffsByStaffIds")
    public ResponseResult<List<DeptStaffVo>> getByStaffIds(@RequestBody List<Long> staffIds) {
        List<DeptStaffVo> staffByStaffId = staffService.getStaffByStaffId(staffIds);
        return ResponseResult.success(staffByStaffId);
    }

    @GetMapping("list")
    public TableDataInfo<StaffVo> list(StaffBo staffBo, PageQuery pageQuery) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            staffBo.setFilterNonAdmin(true);
        }
        return staffService.selectPageUserList(staffBo, pageQuery);
    }

    /**
     * 后台管理点击修改获取信息
     */
    @GetMapping(value = {"/", "{staffId}"})
    public ResponseResult<StaffInfoVo> getStaffInfoById(@PathVariable(value = "staffId", required = false) Long staffId) {
        StaffInfoVo staffInfoVo = new StaffInfoVo();
        List<RoleVo> roles = roleService.selectRoleAll();
        staffInfoVo.setRoles(SecurityUtils.isAdmin(SecurityUtils.getUserId()) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));
        staffInfoVo.setPositions(BeanCopyUtils.copyBeanList(positionService.selectPositionAll(), PositionVo.class));
        if (ObjectUtil.isNotNull(staffId)) {
            StaffVo staff = staffService.selectStaffById(staffId);
            staffInfoVo.setStaff(staff);
            staffInfoVo.setRoleIds(roleService.selectRoleByStaffId(staffId));
            staffInfoVo.setPositionIds(staffPositionService.selectPositionListByStaffId(staffId));
        }
        return ResponseResult.success(staffInfoVo);
    }

    /**
     * 更新员工信息
     */
    @PutMapping("")
    @SaCheckPermission("system:staff:edit")
    public ResponseResult<Void> updateStaffInfo(@RequestBody StaffInfoBo staffInfoBo) {
        staffService.updateStaffInfo(staffInfoBo);
        System.out.println(staffInfoBo);
        return ResponseResult.success();
    }

    /**
     * 添加员工
     */
    @PostMapping("addStaff")
    public ResponseResult<Void> addStaffInfo(@Valid @RequestBody AddStaffBo addStaffBo) {
        //注册用户账号
        User user = new User();
        user.setUsername(addStaffBo.getUsername());
        user.setPassword(addStaffBo.getPassword());
        user.setUserContact(addStaffBo.getUserContact());
        userService.registerUser(user);
        //注册员工账号
        addStaffBo.setUserId(user.getUserId());
        staffService.insertStaff(addStaffBo);
        return ResponseResult.success();
    }
}
